package com.java.exer_3;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class TestDate_1 {
    public static void main(String[] args) {
        /*Date date = new Date();
        System.out.println(date.toLocaleString());
        Date date2 = new Date(date.getTime()+24*60*60*1000);
        System.out.println(date2.toLocaleString());*/

        //封装日期
        Date d1 = getDate(2021, 1, 12, 10, 45, 10, 900);
        System.out.println(getDateStr(d1));

    }

    /**
     * 解析一个Date中的年月日时分秒毫秒
     */
    public static String getDateStr(Date date) {
        //将date对象设置到 日历对象
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        //解析年
        int y = gc.get(Calendar.YEAR);
        //解析月
        int m = gc.get(Calendar.MONTH) + 1;
        //日
        int d = gc.get(Calendar.DAY_OF_MONTH);
        //时
        int h = gc.get(Calendar.HOUR_OF_DAY);
        //分
        int mi = gc.get(Calendar.MINUTE);
        //秒
        int s = gc.get(Calendar.SECOND);
        //毫秒
        int ms = gc.get(Calendar.MILLISECOND);

        return y + "-" + String.format("%02d", m) + "-" + String.format("%02d", d) + " " + h + ":" + mi + ":" + s + " " + ms;
    }

    /**
     * 给定年月日时分秒毫秒的整数，如何封装到日期
     */
    public static Date getDate(int y, int m, int d, int h, int mi, int s, int S) {
        GregorianCalendar gc = new GregorianCalendar(y, m - 1, d, h, mi, s);
        return new Date(gc.getTime().getTime() + S);
    }
}
